package com.ssy.lingxi.component.rabbitMQ.serviceImpl;

import com.ssy.lingxi.component.rabbitMQ.service.IRabbitMQUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * rabbitMQ工具类实现类
 * @author jw.chen
 * @date 2020-08-01
 */
@Service("IRabbitMQUtils")
@ConditionalOnExpression("T(org.springframework.util.StringUtils).hasLength('${spring.rabbitmq.host:}') or T(org.springframework.util.StringUtils).hasLength('${spring.rabbitmq.addresses:}')")
public class RabbitMqUtilsImpl implements IRabbitMQUtils {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送信息
     * @param exchange      交换机
     * @param obj           消息体
     */
    @Override
    public void sendMsg(String exchange, Object obj) {
        //发送信息到MQ
        rabbitTemplate.convertAndSend(exchange, "", obj);
    }

    /**
     * 发送信息
     * @param exchange      交换机
     * @param routingKey    路由键
     * @param obj           消息体
     */
    @Override
    public void sendMsg(String exchange, String routingKey, Object obj) {
        //发送信息到MQ
        rabbitTemplate.convertAndSend(exchange, routingKey, obj);
    }

    /**
     * 发送信息并且等消费端返回
     * @param exchange      交换机
     * @param routingKey    路由键
     * @param obj           消息体
     * @param timeOut       超时时间
     */
    @Override
    public Object sendAndReceiveMsg(String exchange, String routingKey, Object obj, long timeOut) {
        //发送信息到MQ
        return rabbitTemplate.convertSendAndReceive(exchange, routingKey, obj, message -> {
            message.getMessageProperties().setExpiration(String.valueOf(timeOut));
            return message;
        });
    }

    /**
     * 发送信息
     * @param exchange      交换机
     * @param routingKey    路由键
     * @param obj           消息体
     * @param delayTime     延迟时间(单位为ms)
     */
    @Override
    @Deprecated
    public void sendMsg(String exchange, String routingKey, Object obj, long delayTime) {
//        MessageProperties props = new MessageProperties();
//        //消息的延迟时间
//        props.setExpiration(Long.toString(delayTime));
//        Message ttlMessage = new Message(JSONUtil.toJsonStr(obj).getBytes(), props);
//        rabbitTemplate.convertAndSend(exchange, routingKey, ttlMessage);

        rabbitTemplate.convertAndSend(exchange, routingKey, obj, message -> {
            //注意这里时间可以使long，而且是设置header
            message.getMessageProperties().setHeader("x-delay",delayTime);
            return message;
        });
    }

    /**
     * 接收消息
     * @param queueName 队列名称
     */
    @Override
    public Object receiveMsg(String queueName) {
        //接收MQ信息
        return rabbitTemplate.receiveAndConvert(queueName);
    }

}